package com.shushan.mixedexam;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.url.UrlParse;
import com.android.permission.FloatPermissionUtil;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.mixedexam.bean.ExerciseResultBean;
import com.shushan.mixedexam.bean.MutiExercisePaperBean;
import com.shushan.network.UrlConst;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.permission.OpenWindowActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.ControlUtil;
import com.shushan.util.DateUtils;
import com.shushan.util.DialogUtil;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.GoodsDetailWebActivity;

/**
 * @ClassName: MixedExamScoreActivity
 * @Desciption: //混合题型结果界面
 * @author: zhangshihao
 * @date: 2018-08-04
 */
public class MixedExamScoreActivity extends BaseActivity implements View.OnClickListener, Animation.AnimationListener {

    private static final String TAG = MixedExamScoreActivity.class.getSimpleName();

    private ImageView backImageView;
    private TextView getTimeText;
    private ImageView ivSurpriseImg;
    private Button btnWatchTopic, btnContinueExercise;
    private ImageView btnExamAgain;
    private ImageView ivUseNow, ivExchangeReward;
    private LinearLayout ustTimeLayout;
    private TextView tvRewardStarNum;
    private RelativeLayout rlFirstToy;
    private ImageView ivGetSystemToyNow;
    private TextView tvRewardTimeDesc;
    private TextView tvExamScore;

    private ExerciseResultBean exerciseResultBean;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int examType;
    private int subjectId;

    private MutiExercisePaperBean examPaperBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenManager.getInstance().setStatusBar(true, this);
        setContentView(R.layout.exam_score_activity_new);

        exerciseResultBean = (ExerciseResultBean) Session.getSession().get("exerciseResultBean");
        examPaperBean = (MutiExercisePaperBean) Session.getSession().get("examPaperBean");
        examType = getIntent().getIntExtra("examType", 0);
        subjectId = getIntent().getIntExtra("subjectId", 0);

        initView();

        setData();
    }

    private void initView() {
        ustTimeLayout = findViewById(R.id.exam_score_use_time_layout);
        getTimeText = findViewById(R.id.tv_get_time);
        backImageView = findViewById(R.id.top_left_back_img);
        backImageView.setOnClickListener(this);
        ivSurpriseImg = findViewById(R.id.iv_surprise_img);
        btnWatchTopic = findViewById(R.id.btn_watch_topic);
        btnWatchTopic.setOnClickListener(this);
        btnExamAgain = findViewById(R.id.btn_exam_again);
        btnExamAgain.setOnClickListener(this);
        ivUseNow = findViewById(R.id.iv_use_now);
        ivUseNow.setOnClickListener(this);
        ivExchangeReward = findViewById(R.id.iv_exchange_reward);
        ivExchangeReward.setOnClickListener(this);
        tvRewardStarNum = findViewById(R.id.tv_reward_star_num);
        btnContinueExercise = findViewById(R.id.btn_continue_exercise);
        btnContinueExercise.setOnClickListener(this);
        rlFirstToy = findViewById(R.id.rl_first_toy);
        ivGetSystemToyNow = findViewById(R.id.iv_get_system_toy_now);
        ivGetSystemToyNow.setOnClickListener(this);
        tvRewardTimeDesc = findViewById(R.id.tv_reward_time_desc);
        tvExamScore = findViewById(R.id.tv_exam_score);
    }

    private void setData() {
        if (exerciseResultBean != null) {
            int chineseScore = exerciseResultBean.chineseScore;
            int mathScore = exerciseResultBean.mathScore;
            int englishScore = exerciseResultBean.englishScore;
            int subCount = 3;
            if(chineseScore < 0){
                chineseScore = 0;
                subCount--;
            }
            if(mathScore < 0){
                mathScore = 0;
                subCount--;
            }
            if(englishScore < 0){
                englishScore = 0;
                subCount--;
            }
            int score;
            if(exerciseResultBean.score > 0){
                score = exerciseResultBean.score;
            }else {
                if(examType == Constants.TYPE_SYNC_EXERCISE){
                    if(subCount == 0){
                        score = 0;
                    }else {
                        score = (chineseScore + mathScore + englishScore) / subCount;
                    }
                }else{
                    score = chineseScore+mathScore+englishScore;
                }
            }

            tvExamScore.setText(score + "分");

            getTimeText.setText(exerciseResultBean.reward_time + "");
            if (exerciseResultBean.reward_time == 0) {
                ivUseNow.setVisibility(View.GONE);
                tvRewardTimeDesc.setVisibility(View.VISIBLE);
                tvRewardTimeDesc.setText(exerciseResultBean.reward_description);
            }else if(exerciseResultBean.reward_time > 0){
                ControlUtil.addGameTime(exerciseResultBean.reward_time);
            }

            tvRewardStarNum.setText(exerciseResultBean.stars_num + "");
            if(TextUtils.isEmpty(exerciseResultBean.first_toy)) {
                rlFirstToy.setVisibility(View.VISIBLE);
                startSurpriseAnimation(this);
            }
            //将该次练习得到的学贝数记入本地
            shuShanApplication.updateStars(exerciseResultBean.stars_num);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_get_system_toy_now:
            case R.id.btn_get_reward:
                //跳转奖品展示网页
                gotoToyWeb();
                DialogUtil.dismissDialog();
                break;
            case R.id.btn_watch_topic://查看习题
                Session.getSession().put("examPaperBean", examPaperBean);

                Intent intent = new Intent(this, MixedExamActivity.class);
                intent.putExtra(Constants.SCORE_RESULT_JUMP_TYPE, Constants.JUMP_TYPE_TOPICS_WATCH);
                intent.putExtra("examType", examType);
                startActivityAllow(intent);
                break;
            case R.id.btn_exam_again://重考
                startRepeatExam();
                break;
            case R.id.iv_exercise_continue://继续练习
            case R.id.btn_continue_exercise://继续练习
                onBackAction();
                break;
            case R.id.iv_use_now://立即使用手机
                gotoGamesFloat();
                break;
            case R.id.iv_watch_wrong_topic://查看错题
                Session.getSession().put("examPaperBean", examPaperBean);

                Intent intent2 = new Intent(this, MixedExamActivity.class);
                intent2.putExtra(Constants.SCORE_RESULT_JUMP_TYPE, Constants.JUMP_TYPE_WRONG_TOPIC_WATCH);
                intent2.putExtra("examType", examType);
                startActivityAllow(intent2);
                break;
            case R.id.iv_exchange_reward://兑换奖品
                startActivity(MyStarActivity.class);
                break;
            case R.id.iv_get_now://立即领取
                startSurpriseAnimation(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        //do nothing
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        ivSurpriseImg.setVisibility(View.GONE);
                        DialogUtil.showSurpriseDialog(MixedExamScoreActivity.this, null, "领取奖品成功，奖品正飞奔而来！");
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        //do nothing
                    }
                });
                break;
            case R.id.top_left_back_img:
                onBackAction();
                break;
            default:
                break;
        }
    }

    private void gotoToyWeb() {
        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        UserBean currentUserBean = shuShanApplication.getUserBean();
        int childId = currentChildBean.id;
        UrlParse urlParse = new UrlParse(/*UrlConst.BASE_URL*/"https://tpi.shushan.com")
                .appendRegion(UrlConst.DIST_TOY_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "")
                .putValue("starsnum",currentChildBean.stars)
                .putValue("goodsid",0)
                .putValue("viptype",ToolUtils.getVipTypeForGoodsDetails(currentUserBean))
                ;
        Intent intent = new Intent(this, GoodsDetailWebActivity.class);
        intent.putExtra("title", "奖品详情");
        intent.putExtra("url", urlParse.toString());
        startActivityForResultAllow(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 200){
            showToast("领取成功");
            rlFirstToy.setVisibility(View.GONE);
        }else if(resultCode == 500){//玩具详情点击购买
            startActivity(OpenVipSpendActivity.class);
        }
    }

    private void gotoGamesFloat() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl){
            showToast("请先进入家长模式开启管控");
            return;
        }

        boolean isAllowPlay = SharedPreferencesUtils.getBooleanDates(Constants.ALLOW_PLAY_SWITCH_SHAREPREFERS_KEY);
        if(!isAllowPlay){
            showToast("允许学习换取娱乐时间的开关已关闭");
            return;
        }

        if(SystemUtils.checkUsagePermission(this) && FloatPermissionUtil.checkPermission(this)){
            if(exerciseResultBean != null){
                setAllowBack(true);
                ActivityStackManager.getActivityStackManager().popAllActivity();

                GamesFloatWindow gamesFloatWindow = new GamesFloatWindow(shuShanApplication);
                gamesFloatWindow.setPaperId(Integer.parseInt(exerciseResultBean.paper_id));
                GamesWindowManager.setGamesFloatWindow(gamesFloatWindow);
                GamesWindowManager.createGamesFloatWindow(shuShanApplication);

                int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                        + shuShanApplication.getCurrentChildId());
                //开启玩耍手机时间的闹钟
                setChildFree(gameTime);
            }else {
                showToast("考试结果数据为空");
                return;
            }
        }else if(! FloatPermissionUtil.checkPermission(this)){
            showNoFloatDialog();
        } else if(!SystemUtils.checkUsagePermission(this)){
            showNoUsageDialog();
        }
    }

    private void setChildFree(int freeTime) {
        Log.i(TAG, "freeTime=" + freeTime + " setChildFree:" + DateUtils.getNowDate());

        if (freeTime > 0) {
            ToolUtils.setLockAlarm(this, freeTime);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    private void showNoFloatDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您的手机没有授予悬浮窗权限，请开启后再试")
                .setNegativeButton("暂不开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("现在去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenWindowActivity.class);
                    }
                })
                .create().show();
    }

    private void startRepeatExam() {
        onBackAction();
        Session.getSession().put("examPaperBean", examPaperBean);

        Intent intent = new Intent(this, MixedExamActivity.class);
        intent.putExtra("examType", examType);
        intent.putExtra(Constants.SCORE_RESULT_JUMP_TYPE, Constants.JUMP_TYPE_EXAM_REPEAT);
        startActivityAllow(intent);
    }

    private void startSurpriseAnimation(Animation.AnimationListener listener) {
        ivSurpriseImg.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.scale_normal_to_harf);
        ivSurpriseImg.setAnimation(animation);
        ivSurpriseImg.startAnimation(animation);
        animation.setAnimationListener(listener);
    }

    @Override
    public void onAnimationStart(Animation animation) {
        //do nothing
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        ivSurpriseImg.setVisibility(View.GONE);
        DialogUtil.showSurpriseDialog(this, this);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        //do nothing
    }

}
